import asyncio

import falcon
import falcon.asgi
import json
from datetime import datetime

from WebBackend.dataclass.TaskItem import TaskItem, TaskStatus
from WebBackend.middleware.virtualWorldGate_Chuche import login_require
from WebBackend.store.TaskStore import TaskStore


@falcon.before(login_require)
class TaskCenterAPI:
    def __init__(self, task_store: TaskStore):
        self.task_store = task_store

    async def on_get(self, req: falcon.Request, resp: falcon.Response):
        # 获取所有任务并转换为指定格式
        tasks = await self.task_store.list_tasks()
        response_data: list[TaskItem | any] = []
        for task_dict in tasks:
            start_time = datetime.fromisoformat(task_dict["started_at"]) if task_dict["started_at"] else None
            end_time = datetime.fromisoformat(task_dict["finished_at"]) if task_dict["finished_at"] else None
            duration = (end_time - start_time).total_seconds() if (start_time and end_time) else 0
            response_data.append({
                "task_id": task_dict["task_id"],
                "cmd": task_dict["command"],
                "start_time": task_dict["started_at"],
                "duration": duration,
                "end_time": task_dict["finished_at"],
                "progress": task_dict["status"],
                "status": task_dict["status"]
            })

        resp.media = response_data


class TaskDetailResource:
    def __init__(self, task_store: TaskStore):
        self.task_store = task_store

    async def on_get(self, req, resp, task_id):
        task = await self.task_store.get_task(task_id)
        if not task:
            raise falcon.HTTPNotFound(description="Task not found")

        resp.text = json.dumps(task.to_dict())
        resp.content_type = falcon.MEDIA_JSON
        resp.status = falcon.HTTP_200

    async def on_delete(self, req, resp, task_id):
        success = await self.task_store.cancel_task(task_id)
        if not success:
            raise falcon.HTTPNotFound(description="Task not found or cannot be cancelled")

        resp.status = falcon.HTTP_204


class TaskCreateResource:
    def __init__(self, task_store: TaskStore):
        self.task_store = task_store

    async def on_post(self, req, resp):
        try:
            data = await req.get_media()
            command = data.get("cmd")
            timeout = data.get("timeout")

            if not command:
                raise falcon.HTTPBadRequest(description="Command is required")

            task = await self.task_store.create_task(command, timeout)
            asyncio.create_task(task.execute())

            resp.text = json.dumps({"id": task.task_id})
            resp.content_type = falcon.MEDIA_JSON
            resp.status = falcon.HTTP_201
        except json.JSONDecodeError:
            raise falcon.HTTPBadRequest(description="Invalid JSON")
